<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="search">
        <el-form ref="queryFormRef" :model="queryParams" :inline="true">
          <el-form-item label="农田名称" prop="name">
            <el-input style="width: 120px" v-model="queryParams.name" placeholder="请输入" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="农田性质">
            <el-select placeholder="请选择" style="width: 120px" v-model="queryParams.type">
              <el-option v-for="item in FARM_OPTIONS" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="牵头部门">
            <el-select placeholder="请选择" style="width: 120px" v-model="queryParams.deptId">
              <el-option v-for="item in departList" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
            <el-button type="primary" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain @click="handleActive">启用</el-button>
            <el-button type="primary" plain @click="handleForbidden">禁用</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-dropdown class="mt-[1px]">
              <el-button plain type="info">
                更多
                <el-icon class="el-icon--right"><arrow-down /></el-icon
              ></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <!-- <el-dropdown-item icon="Download" @click="importTemplate">下载模板</el-dropdown-item> -->
                  <!-- 注意 由于el-dropdown-item标签是延迟加载的 所以v-has-permi自定义标签不生效 需要使用v-if调用方法执行 -->
                  <!-- <el-dropdown-item icon="Top" @click="handleImport">导入数据</el-dropdown-item> -->
                  <el-dropdown-item icon="Download" @click="handleExport">导出数据</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
          <right-toolbar v-model:show-search="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="farmList" @selection-change="handleSelectionChange" @cell-dblclick="cellDbClick">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column v-if="false" label="主键" align="center" prop="id" />
        <el-table-column label="农田编码" align="center" width="140" prop="code"> </el-table-column>
        <el-table-column label="农田名称" align="center" prop="name" width="120" />
        <el-table-column label="农田性质" align="center" prop="type" width="120" :formatter="formatType" />
        <el-table-column label="是否高标准农田" align="center" prop="isHighStandard" width="120" :formatter="formatHighStandard" />
        <el-table-column label="牵头部门" align="center" prop="deptName" width="120" />
        <el-table-column label="建设年度" align="center" prop="buildYear" />
        <el-table-column label="土地所有权" align="center" prop="ownership" width="120" :formatter="formatOwnership" />
        <el-table-column label="项目名称" align="center" prop="projectName" />
        <el-table-column label="农作物" align="center" prop="crop" />
        <el-table-column label="面积" align="center" prop="size" />
        <el-table-column label="亩产量" align="center" prop="production" />
        <!-- <el-table-column label="图片" align="center" prop="pic">
          <template #default="scope">
            <ImagePreview :width="100" :height="100" :src="scope.row.pic" :preview-src-list="[scope.row.pic]" />
          </template>
        </el-table-column> -->
        <el-table-column label="电子围栏编码" align="center" prop="eFenceCode" width="160" />
        <el-table-column label="农田介绍" align="center" prop="introduction" width="200">
          <template #default="scope">
            <div v-html="scope.row.introduction"></div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" :formatter="formatStatus" />
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>

    <!-- 用户导入对话框 -->
    <el-dialog v-model="upload.open" :title="upload.title" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload">
          <i-ep-upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="text-center el-upload__tip">
            <div class="el-upload__tip"><el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据</div>
            <span>仅允许导入xls、xlsx格式文件。</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Leave" lang="ts">
import { listFarmLand, getDepart, handleFormStatus } from '@/api/farm/index';
import { FarmLandQuery, FarmLandForm, FarmLandVO, DepartVO, StatusForm } from '@/api/farm/types';
import { FARM_OPTIONS, LAND_OPTIONS } from '@/constants/options';
import { globalHeaders } from '@/utils/request';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const farmList = ref<FarmLandVO[]>([]);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const codes = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const departList = ref<DepartVO[]>([]);

const uploadRef = ref<ElUploadInstance>();
const queryFormRef = ref<ElFormInstance>();
/*** 用户导入参数 */
const upload = reactive<ImportOption>({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: '',
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: globalHeaders(),
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + '/system/user/importData'
});

const data = reactive<PageData<FarmLandForm, FarmLandQuery>>({
  form: {},
  queryParams: {
    pageNo: 1,
    pageSize: 10
  },
  rules: {}
});

const { queryParams } = toRefs(data);

const formatType = (row, column, cellValue, index) => {
  let selType = FARM_OPTIONS.filter((item) => item.value === row.type);

  return selType.length > 0 ? selType[0].label : '';
};
const formatHighStandard = (row, column, cellValue, index) => {
  return row.isHighStandard ? '是' : '否';
};
const formatOwnership = (row, column, cellValue, index) => {
  let selType = LAND_OPTIONS.filter((item) => item.value === row.ownership);

  return selType.length > 0 ? selType[0].label : '';
};
const formatStatus = (row, column, cellValue, index) => {
  return row.status ? '启用' : '禁用';
};

/** 查询列表 */
const getList = async () => {
  loading.value = true;
  const res = await listFarmLand(queryParams.value);
  const { data } = res;
  farmList.value = data.records;

  total.value = data.total;
  loading.value = false;
};

/** 查询部门 */
const getDepartList = async () => {
  loading.value = true;
  const res = await getDepart();
  const { data } = res;

  departList.value = data;
  loading.value = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNo = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  queryParams.value.pageNo = 1;
  queryParams.value.name = undefined;
  queryParams.value.type = undefined;
  queryParams.value.deptId = undefined;
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: FarmLandVO[]) => {
  ids.value = selection.map((item) => item.id);
  codes.value = selection.map((item) => item.code);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  // proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: `/farm/land/edit`,
    query: {
      type: 'add'
    }
  });
};
//双击进行修改
const cellDbClick = (row, column, cell, event) => {
  handleUpdate(row);
};

/** 修改按钮操作 */
const handleUpdate = (row?: FarmLandVO) => {
  // proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: `/farm/land/edit`,
    query: {
      id: row.id,
      type: 'edit'
    }
  });
};

/** 查看按钮操作 */
const handleView = (row?: FarmLandVO) => {
  // proxy.$tab.closePage(proxy.$route);
  proxy.$router.push({
    path: `/farm/land/edit`,
    query: {
      id: row.id,
      type: 'view'
    }
  });
};

/** 启用操作 */
const handleActive = async (row?: FarmLandVO) => {
  const _ids = row?.id || ids.value;
  const _codes = row?.code || codes.value;
  if (ids.value.length == 0) {
    proxy?.$modal.msgError('请先选数据');
    return false;
  }

  await proxy?.$modal.confirm('是否确认启用为"' + _codes + '"的数据项？').finally(() => (loading.value = false));

  await handleFormStatus(_ids, true);
  proxy?.$modal.msgSuccess('启用成功');
  await getList();
};
/** 禁用用操作 */
const handleForbidden = async (row?: FarmLandVO) => {
  const _ids = row?.id || ids.value;
  const _codes = row?.code || codes.value;
  if (ids.value.length == 0) {
    proxy?.$modal.msgError('请先选数据');
    return false;
  }

  await proxy?.$modal.confirm('是否确认禁用为"' + _codes + '"的数据项？').finally(() => (loading.value = false));

  await handleFormStatus(_ids, false);
  proxy?.$modal.msgSuccess('禁用成功');
  await getList();
};

/** 下载模板操作 */
const importTemplate = () => {
  proxy?.download('system/user/importTemplate', {}, `land_${new Date().getTime()}.xlsx`);
};

/** 导入按钮操作 */
const handleImport = () => {
  upload.title = '用户导入';
  upload.open = true;
};

/** 提交上传文件 */
function submitFileForm() {
  uploadRef.value?.submit();
}
/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'base/farmland/export',
    {
      ...queryParams.value
    },
    `land_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
  getDepartList();
});
</script>
